<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { FieldVO } from '#/api/config/search/model';

import { computed } from 'vue';

import { useAccess } from '@vben/access';
import { Fallback, Page, useVbenDrawer } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { $t } from '@vben/locales';
import { eachTree, getVxePopupContainer } from '@vben/utils';

import { Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { fieldPage, fieldRemove } from '#/api/config/search';
import { getDictOptions } from '#/utils/dict';
import { renderDictTags } from '#/utils/render';
import { preserveTreeTableState } from '#/views/system/menu/helper';

import { columns, querySchema } from './data';
import searchDrawer from './search-drawer.vue';

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

const gridOptions: VxeGridProps = {
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    enabled: false,
  },
  proxyConfig: {
    ajax: {
      query: async (_, formValues = {}) => {
        const resp = await fieldPage({
          ...formValues,
        });
        const list = resp.map((item) => {
          item.id = item.pageNo;
          item.name = item.pageNo;
          item.type = 'page';
          item.component = 'Page';

          if (item.fields?.length > 0) {
            item.fields = item.fields.map((sub) => {
              sub.name = sub.label;
              sub.type = 'field';
              return sub;
            });
          }
          return item;
        });
        return { rows: list };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  /**
   * 开启虚拟滚动
   * 数据量小可以选择关闭
   * 如果遇到样式问题(空白、错位 滚动等)可以选择关闭虚拟滚动
   */
  scrollY: {
    enabled: false,
    gt: 0,
  },
  treeConfig: {
    parentField: 'pageNo',
    rowField: 'id',
    // 自动转换为tree 由vxe处理 无需手动转换
    // transform: false,
    childrenField: 'fields',
    expandAll: true,
  },
  id: 'config-search-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    cellDblclick: (e) => {
      const { row = {} } = e;
      if (!row?.fields) {
        return;
      }
      const isExpanded = row?.expand;
      tableApi.grid.setTreeExpand(row, !isExpanded);
      row.expand = !isExpanded;
    },
    // 需要监听使用箭头展开的情况 否则展开/折叠的数据不一致
    toggleTreeExpand: (e) => {
      const { row = {}, expanded } = e;
      row.expand = expanded;
    },
  },
});
const [SearchDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: searchDrawer,
});

function handleAdd() {
  drawerApi.setData({});
  drawerApi.open();
}

function handleSubAdd(row: FieldVO) {
  const { pageNo } = row;
  drawerApi.setData({ pageNo, update: false });
  drawerApi.open();
}

async function handleEdit(record: FieldVO) {
  drawerApi.setData({ id: record.id, pageNo: record.pageNo, update: true });
  drawerApi.open();
}

async function handleDelete(row: FieldVO) {
  await preserveTreeTableState(tableApi, async () => {
    await fieldRemove([row.id]);
    await tableApi.query();
  });
}

function removeConfirmTitle(row: FieldVO) {
  return `是否确认删除字段 [${row.label}] ?`;
}

/**
 * 编辑/添加成功后刷新表格
 */
async function afterEditOrAdd() {
  await preserveTreeTableState(tableApi, () => tableApi.query());
}

/**
 * 全部展开/折叠
 * @param expand 是否展开
 */
function setExpandOrCollapse(expand: boolean) {
  eachTree(tableApi.grid.getData(), (item) => (item.expand = expand));
  tableApi.grid?.setAllTreeExpand(expand);
}

/**
 * 与后台逻辑相同
 * 只有租户管理和超级管理能访问菜单管理
 * 注意: 只有超管才能对菜单进行`增删改`操作
 * 注意: 只有超管才能对菜单进行`增删改`操作
 * 注意: 只有超管才能对菜单进行`增删改`操作
 */
const { hasAccessByRoles } = useAccess();
const isAdmin = computed(() => {
  return hasAccessByRoles(['admin', 'superadmin']);
});
</script>

<template>
  <Page v-if="isAdmin" :auto-content-height="true">
    <BasicTable>
      <template #table-title>
        <main-title text="字段列表" />
      </template>
      <template #toolbar-tools>
        <Space>
          <a-button @click="setExpandOrCollapse(false)">
            {{ $t('pages.common.collapse') }}
          </a-button>
          <a-button @click="setExpandOrCollapse(true)">
            {{ $t('pages.common.expand') }}
          </a-button>
          <a-button
            type="primary"
            v-access:code="['search:field:add']"
            v-access:role="['superadmin']"
            @click="handleAdd"
          >
            {{ $t('pages.common.add') }}
          </a-button>
        </Space>
      </template>
      <template #operates="{ row }">
        <div class="py-[10px]">
          <component
            v-if="row.operates"
            :is="
              renderDictTags(
                row.operates?.split(','),
                getDictOptions(DictEnum.QUERY_OPERATE_TYPE),
                false,
                2,
              )
            "
          />
        </div>
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-if="row.type === 'field'"
            v-access:code="['search:field:edit']"
            v-access:role="['superadmin']"
            @click="handleEdit(row)"
          >
            {{ $t('pages.common.edit') }}
          </ghost-button>
          <ghost-button
            v-if="row.type === 'page'"
            class="btn-success"
            v-access:code="['search:field:add']"
            v-access:role="['superadmin']"
            @click="handleSubAdd(row)"
          >
            {{ $t('pages.common.add') }}
          </ghost-button>
          <Popconfirm
            v-if="row.type === 'field'"
            :get-popup-container="getVxePopupContainer"
            placement="left"
            :title="removeConfirmTitle(row)"
            @confirm="handleDelete(row)"
          >
            <ghost-button
              danger
              v-access:code="['search:field:remove']"
              v-access:role="['superadmin']"
              @click.stop=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <SearchDrawer @reload="afterEditOrAdd" />
  </Page>
  <Fallback v-else description="您没有高级筛选的访问权限" status="403" />
</template>
